package com.ia.uniweb.cass;

import java.util.concurrent.atomic.AtomicBoolean;

import me.prettyprint.hector.api.Cluster;
import me.prettyprint.hector.api.Keyspace;
import me.prettyprint.hector.api.factory.HFactory;

public class CassandraProxy {

	private static CassandraProxy cassandra;

	private static final String TEST_CLUSTER = "Test Cluster";

	private static final String KEY_SPACE = "University";

	private volatile Cluster cluster;

	private volatile Keyspace keySpace;

	private AtomicBoolean initialised = new AtomicBoolean(false);

	private CassandraProxy() {

	}

	public void init() {

		// Connect to cassandra service
		if (!initialised.getAndSet(true)) {
			cluster = HFactory.getOrCreateCluster(TEST_CLUSTER,
					"localhost:9160");
			keySpace = HFactory.createKeyspace(KEY_SPACE, cluster);
		} else {

			System.out.println("Already initialized");

		}

		System.out.println("Connected to cassandra @localhost");

	}

	public Keyspace getConnectedKeyspace() {
		return this.keySpace;
	}

	public static synchronized CassandraProxy initialise() {

		if (cassandra == null) {
			cassandra = new CassandraProxy();
			cassandra.init();
		}

		return cassandra;
	}

	public static CassandraProxy getCassandra() {
		return cassandra;
	}
}
